//
//  KSOSAddContactController.m
//  Keping
//
//  Created by a on 2017/9/18.
//  Copyright © 2017年 柯平. All rights reserved.
//  好友列表+黑名单好友列表

#import "KSOSAddContactController.h"
#import "KSOSRequest.h"
#import "KSosListModel.h"
#import "GPContactRequest.h"


#import "KSOSAddContactCell.h"

@interface KSOSAddContactController ()<UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate>
/**
 tableview
 */
@property(nonatomic,weak)UITableView*tableView;
/**
 头部搜索栏
 */
@property(nonatomic,weak)UIView*headerView;
/**
 搜索
 */
@property(nonatomic,weak)UITextField * searchView;

/**
 数据源
 */
@property(nonatomic,strong)NSMutableArray*dataAry;


@end

@implementation KSOSAddContactController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    
    [self loadData];
}

-(void)setUI
{
    if (self.vcType == KSOSAddContactVcTypeSOSContact) {
        self.navigationItem.title=@"Add New Contact";
    }else{
        self.navigationItem.title = @"Block Users";
    }
    
    //头部搜索栏
    UIView*headerView=[[UIView alloc]init];
    [self.view addSubview:headerView];
    self.headerView=headerView;
    
    UITextField * searchView = [[UITextField alloc]init];
    searchView.textAlignment=NSTextAlignmentCenter;
    searchView.backgroundColor=[UIColor colorWithHexString:@"#6d52fb"];
    searchView.layer.masksToBounds=YES;
    searchView.delegate = self;
    searchView.textColor=[UIColor whiteColor];
    searchView.returnKeyType = UIReturnKeySearch;
    searchView.enablesReturnKeyAutomatically = YES;
    [searchView addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [headerView addSubview:searchView];
    searchView.placeholder=@"Search";
    self.searchView=searchView;
    
    
    UITableView*tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate=self;
    tableView.dataSource=self;
    [self.view addSubview:tableView];
    tableView.tableFooterView=[UIView new];
    self.tableView=tableView;
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.headerView.frame=CGRectMake(0, 0, self.view.width, K_FactorH(65));
    self.headerView.hidden = NO;
    
    CGFloat H= K_FactorH(45);
    self.searchView.frame=CGRectMake(K_FactorW(25),(self.headerView.height-H)/2, self.headerView.width-2*K_FactorW(25), H);
    self.searchView.layer.cornerRadius=self.searchView.height/2;
    
    
    if (self.vcType == KSOSAddContactVcTypeBlockUsers) {
        //隐藏搜索栏
        self.headerView.frame = CGRectMake(0, 0, self.view.width, 0);
        self.headerView.hidden = YES;
    }
    
    self.tableView.frame=CGRectMake(0, CGRectGetMaxY(self.headerView.frame), self.view.width, self.view.height-CGRectGetMaxY(self.headerView.frame));
}
#pragma mark -- UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataAry.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KSOSAddContactCell*cell=[KSOSAddContactCell cellWithTableView:tableView];
    cell.listModel = self.dataAry[indexPath.row];
    cell.isBlock = (self.vcType == KSOSAddContactVcTypeBlockUsers);
    WEAKSELF
    cell.callback = ^(KSosListModel *listModel) {
      
        if (weakSelf.vcType == KSOSAddContactVcTypeSOSContact) {
            
            //增加
            [weakSelf showLoading];
            KSOSRequest *addRequest = [[KSOSRequest alloc] initWithURL:kSosAddFriendURL];
            addRequest.params = @{@"friendId":listModel.friendId};
            [addRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
                
                [weakSelf hideHUD];
                
                NSDictionary *response = request.responseJSONObject;
                if ([response[@"statusCode"] integerValue] != 200) {
                    
                    [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
                    return;
                }
                
                
            } failure:^(__kindof KBaseRequest * _Nonnull request) {
                [weakSelf hideHUD];
                [weakSelf showError:request.error];
                
            }];
        }else {
            //移除黑名单
            NSString *url = [kIMAlterUserInfoURL stringByReplacingOccurrencesOfString:@"{userId}" withString:listModel.friendId];
            GPContactRequest *request = [[GPContactRequest alloc] initWithURL:url];
            NSString *isBlock = @"N";
            request.isPost = YES;
            request.params = @{@"isBlock":isBlock};
            [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
                
                NSDictionary *response = request.responseJSONObject;
                
                if ([response[@"statusCode"] integerValue] != 200) {
                    
                    [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
                    
                    return;
                }
                
                [self showSuccess:@"Success"];
                [self loadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"kRemoveBlackUserSuccessNotification" object:nil];
                
            } failure:^(__kindof KBaseRequest * _Nonnull request) {
                
                [self showErrorText:@"Error"];
            }];
            
            
            
        }
    };
    
    return cell;;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return K_FactorH(75);
}


#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *key = textField.text;
    
    //发起搜索请求
    [self showLoading];
    KSOSRequest *searchRequest =  [[KSOSRequest alloc] initWithURL:kSosSearchFriendsURL];
    searchRequest.params = @{@"searchContent":key};
    [searchRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        
        [self hideHUD];
        NSDictionary *response = request.responseJSONObject;
        if ([response[@"statusCode"] integerValue] != 200) {
            
            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            return;
        }
        
        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in response[@"relationFriendViews"]) {
            KSosListModel *model = [KSosListModel modelWithDictionary:dict];
            [arrayM addObject:model];
        }
        
        self.dataAry = [NSMutableArray arrayWithArray:arrayM];
        [self.tableView reloadData];
        
        NSLog(@"----->Smallyou:%@", response);
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        [self showError:request.error];
    }];
    
    
    return YES;
}

- (void)textFieldValueChanged:(UITextField *)textField
{
    NSString *key = textField.text;
    if (key.length == 0) {
        //获取数据
        [self loadData];
    }
}



- (void)loadData
{
    [self showLoading];
    KSOSRequest *listRequest =  [[KSOSRequest alloc] initWithURL:kSosGetFriendsListURL];
    if (self.vcType == KSOSAddContactVcTypeSOSContact) {
        listRequest.params = @{@"isBlock":@""};
    }else{
        listRequest.params = @{@"isBlock":@"Y"};
    }
    [listRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        
        [self hideHUD];
        NSDictionary *response = request.responseJSONObject;
        if ([response[@"statusCode"] integerValue] != 200) {
            
            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            return;
        }
    
        
        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in response[@"relationFriendViews"]) {
            KSosListModel *model = [KSosListModel modelWithDictionary:dict];
            [arrayM addObject:model];
        }
        
        self.dataAry = [NSMutableArray arrayWithArray:arrayM];
        [self.tableView reloadData];
        
        if (self.vcType == KSOSAddContactVcTypeBlockUsers) {
            self.title = [NSString stringWithFormat:@"Block Users(%zd)", arrayM.count];
        }
        
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        
        [self hideHUD];
        [self showError:request.error];

        
    }];
}


- (void)loadDataWithCallback:(void(^)(BOOL success, NSArray<KSosListModel *> *array, NSString *errMsg))completion
{
    KSOSRequest *listRequest =  [[KSOSRequest alloc] initWithURL:kSosGetFriendsListURL];
    if (self.vcType == KSOSAddContactVcTypeSOSContact) {
        listRequest.params = @{@"isBlock":@""};
    }else{
        listRequest.params = @{@"isBlock":@"Y"};
    }
    [listRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        
        
        NSDictionary *response = request.responseJSONObject;
        if ([response[@"statusCode"] integerValue] != 200) {
            
            if (completion) {
                completion(NO, nil, response[@"msg"]);
            }
            return;
        }
        
        
        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in response[@"relationFriendViews"]) {
            KSosListModel *model = [KSosListModel modelWithDictionary:dict];
            [arrayM addObject:model];
        }
        
        if (completion) {
            completion(YES, arrayM, nil);
        }
        
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        
        if (completion) {
            completion(NO, nil, @"failture");
        }
        
    }];
}





@end
